import os
import sys
import fileinput
import shutil
import tempfile
from distutils.sysconfig import get_python_lib

'''
	The rewrite function takes three parameters.  srcfile which is the file that needs to be modified, searchPattern which is the string
	that is searched for in the srcfile and replaceStr is the string to replace searchPattern with
'''
def rewrite(srcfile,searchPattern,replaceStr):
	dstfile = srcfile + '.bak'
	
	#Checks to see if the file has been backed up if not then create a backup of the file.
	if not os.path.isfile(dstfile):
		shutil.copy(srcfile,dstfile)
	
	#creates a temporary file in the same directory that the "executable" was launched from
	tmpfilename = str(os.getpid())
	tfile = open(tmpfilename,'w')
	src = open(srcfile,'r')

	#loops through the entire file changing text
	for line in src:
		if searchPattern in line:
			tfile.write(line.replace(searchPattern,replaceStr))
		else:
			tfile.write(line)
	tfile.close()
	src.close()

	#overwrites the srcfile and deletes the temp file
	shutil.copy2(tmpfilename,srcfile)
	os.unlink(tmpfilename)
	
'''
	The rewriteServerAddressAGtk function is called to modify the URLs in the AccessGrid Toolkit.  It takes one parameter, AGtkdir 
	which is the location to the AccessGrid Toolkit in python's site library folder
'''
def rewriteVenueServerAddressAGtk(AGtkdir):
	#backupext = str(os.getpid()) + '.bak' 
        tempfile = AGtkdir
	filelist = ['ClientProfile.py','VenueCache.py','Preferences.py','QuickBridgeClient.py','RssReader.py','UIUtilities.py','UMTPClient.py','UMTP.py','Utilities.py','VenueClientUI.py','VenueServer.py']
	for pyfile in filelist:
		tempfile = os.path.join(tempfile,pyfile)
		if not os.path.isfile(tempfile):
			print "Could not find file: ", tempfile
			sys.exit(-1)
		print "starting to modify " ,tempfile
		rewrite(tempfile,'mcs.anl.gov','accessgrid.org')
		print "finish modifying " ,tempfile
		tempfile = AGtkdir

'''
	The rewriteServerAddressUserPref function is called to modify the URLs in the User's AccessGrid directory.  It takes one parameter,
	homeprefdir.
'''
def rewriteVenueServerAddressUserPref(homeprefdir):
	#backupext = str(os.getpid()) + '.bak' 
	tempfile = homeprefdir
	filelist = ['preferences','profile']
	for pyfile in filelist:
		tempfile = os.path.join(tempfile,pyfile)
		if not os.path.isfile(tempfile):
			print "Could not find file: ", tempfile
			sys.exit(-1)
		print "starting to modify " ,tempfile
		rewrite(tempfile,'mcs.anl.gov','accessgrid.org')
		print "finish modifying " ,tempfile
		tempfile = homeprefdir
		
'''
	The disableBugReportClientVenueUI function is called to modify the "action-listener" that binds the "Submit Bug" report menu to
	the callback function.  It takes one parameter, AGtkdir which is the location to the AccessGrid Toolkit in python's site library folder
'''
def disableBugReportClientVenueUI(AGtkdir):
	ClientVenueUIFile = os.path.join(AGtkdir,"VenueClientUI.py")
	if not os.path.isfile(ClientVenueUIFile):
		print "Could not locate ClientVenueUI.py file in AGToolkit"
		sys.exit(-1)

		print "starting to modify " , ClientVenueUIFile
	rewrite(ClientVenueUIFile,'wx.EVT_MENU(self, self.ID_HELP_BUG_REPORT, self.SubmitBugCB)','#wx.EVT_MENU(self, self.ID_HELP_BUG_REPORT, self.SubmitBugCB)') 	
	print "finish modifying " , ClientVenueUIFile

'''
	The testPerms function tests to see if the user has write access to the files in the AG Toolkit directory.  Returns y if they do
	or n if they dont.
''' 

def testPerms(AGtkdir):
	testfilename = os.path.join(AGtkdir,"VenueClient")
	testfile = 0
	try:
		testfile = open(testfilename,'w')
	except:
		file_perm = 'n'
	else:
		file_perm = 'y'
		testfile.close()

	return file_perm


if __name__ == "__main__":
	print '''Caution: This script will overwrite certain files in the AccessGrid and your user preference.  
Before running this script it is recommended that you backup all AccessGrid material.
'''
	userBackup = raw_input("Do you wish to continue(Y/n):").lower()
	if userBackup == 'n':
		sys.exit(-1)

	#determines where python's site package directory is located to get access to AccessGrid's toolkit files
        site_packages_dir = get_python_lib()
        site_packages_dir = os.path.join(get_python_lib(),"AccessGrid") 
	if not os.path.exists(site_packages_dir):
		print "Cannot locate AccessGrid libs"
		sys.exit(-1)

	#determines where the user's preferences and configuration is stored
	user_config_accessgrid_dir = os.path.expanduser('~')
	user_config_accessgrid_dir = os.path.join(user_config_accessgrid_dir,".AccessGrid3","Config")
	if not os.path.exists(user_config_accessgrid_dir):
		print "Cannot locate user's AccessGrid config"
		sys.exit(-1)

	convUrlsAGtk = raw_input("Do you wish to modify files in the AG Toolkit directory(y/n):").lower()
	if convUrlsAGtk == 'y':
		canChange = testPerms(site_packages_dir)
		if canChange == 'y':
			print "Starting URL renaming from mcs.anl.gov to accessgrid.org in AG Toolkit Directory"
			rewriteVenueServerAddressAGtk(site_packages_dir)
			print "Disabling Submit Bug action in VenueClient UI"
			disableBugReportClientVenueUI(site_packages_dir)
		else:
			print "Permission Denied accessing files in ", site_packages_dir
			exitPatch = raw_input("Do you wish to continue with the AGpatch application(y/n)").lower()
			if exitPatch == 'n':
				sys.exit(-1)
			else:
				convUrlsAGtk == 'n'

	changeUserConf = raw_input("Do you wish to modify files in your home preference directories(y/n):").lower()
	if changeUserConf == 'y':
		print "Starting URL renaming from mcs.anl.gov to accessgrid.org in User's AccessGrid Configuration Directory"
		rewriteVenueServerAddressUserPref(user_config_accessgrid_dir)

	if convUrlsAGtk == 'y' or changeUserConf == 'y':
		print "URL changes and Submit Bug disabling complete"
	else:
		print "Finish executing with no modifications"
